package ee.battleship.filters;

import java.io.IOException;
import java.util.Calendar;
import java.util.GregorianCalendar;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet Filter implementation class GZIPFilter
 */
@WebFilter(filterName="GZIPFilter",urlPatterns={"*.jsp","*.html","*.js","*.css"})
public class GZIPFilter implements Filter {

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		if (request instanceof HttpServletRequest) {
			HttpServletRequest req = (HttpServletRequest) request;
			HttpServletResponse resp = (HttpServletResponse) response;
			String ae = req.getHeader("accept-encoding");
			if (ae != null && ae.indexOf("gzip") != -1) {
//				System.out.println("GZIP supported, compressing.");
				GZIPResponseWrapper wrappedResponse = new GZIPResponseWrapper(resp);
				chain.doFilter(request, wrappedResponse);
				wrappedResponse.finishResponse();
				return;
			}
			
			// Cache 
			Calendar inTwoMonths = new GregorianCalendar();
	        inTwoMonths.add(Calendar.MONTH, 2);
	        resp.setDateHeader("Expires", inTwoMonths.getTimeInMillis());
			
			chain.doFilter(request, response);
		}
	}

	public void init(FilterConfig filterConfig) {
		// noop
	}

	public void destroy() {
		// noop
	}
	
}
